package top.zdkhqh;


import com.jfinal.kit.StrKit;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author HuangQihan
 * @date 2019/9/9
 **/
public class FileUtil {

    /**
     * 获取文件夹下所有的文件名
     *
     * @param url
     * @return
     */
    public static List<String> getAllFileName(String url) {
        if (StrKit.isBlank(url)) return Collections.emptyList();
        File file = new File(url);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files == null || files.length == 0) return Collections.emptyList();
            return Arrays.stream(files).filter(File::isFile).map(File::getName).collect(Collectors.toList());
        } else {
            throw new IllegalArgumentException("不是文件夹：" + url);
        }
    }

    /**
     * @param url
     * @param fileNameCount 文件数量
     * @return
     */
    public static List<String> getAllFileName(String url, int fileNameCount) {
        List<String> names = getAllFileName(url);
        if (names == null) return Collections.emptyList();
        return getNames(names, fileNameCount);
    }

    private static List<String> getNames(List<String> names, int fileNameCount) {
        if (names.size() >= fileNameCount) {
            return names.subList(0, fileNameCount);
        } else {
            if (fileNameCount - names.size() <= names.size()) {
                names.addAll(names.subList(0, fileNameCount - names.size()));
            } else {
                names.addAll(new ArrayList<>(names));
            }
            return getNames(names, fileNameCount);
        }
    }

    public static void main(String[] args) {
        int len = 100;
        List<String> b = new ArrayList<>();
        for (int i = 0; i < 95; i++) {
            b.add(i + "");
        }
        b = getNames(b, len);
        b.forEach(System.err::println);
        System.err.println(b.size());
    }

}
